﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NLog;
using PMBF.Web.Image.Common;
using PMBF.Application.Api;


namespace PMBF.Web.Image.Controllers
{
    public class ImageController : Controller
    {
        private IHttpContextAccessor _httpContextAccessor;
        private static Logger logger = LogManager.GetCurrentClassLogger();

        public ImageController(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        [HttpGet]
        public ActionResult Save(string id, string url)
        {
            ResultStruct result = new ResultStruct();
            string saveFilePath = Path.Combine(Config.SaveBasePath, ImageService.CreateDirPath(id));
            if (!Directory.Exists(saveFilePath))
            {
                Directory.CreateDirectory(saveFilePath);
            }
            saveFilePath = Path.Combine(saveFilePath, id);
            if (string.IsNullOrEmpty(url))
            {
                HttpRequest request = _httpContextAccessor.HttpContext.Request;
                IFormFile file = request.Form.Files[0];
                if (file == null)
                {
                    result.code = "001";
                    result.msg = "空文件上传";
                    return Json(result);
                }
                try
                {
                    using (var stream = System.IO.File.Create(saveFilePath))
                    {
                        file.CopyToAsync(stream);
                    }
                }
                catch (Exception ex)
                {
                    logger.Info("接收上传文件:" + ex.Message + ":" + saveFilePath);
                    logger.Info(ex.StackTrace);
                    throw;
                }
            }
            else
            {
                WebClient client = new WebClient();
                try
                {
                    client.DownloadFile(url, saveFilePath);
                }
                catch (Exception ex)
                {
                    logger.Info("下载资源服务器文件:" + ex.Message + ":" + saveFilePath + ":" + url);
                    logger.Info(ex.StackTrace);
                    throw;
                }
            }
            result.obj = saveFilePath;
            return Json(result);
        }

        [ResponseCache(Duration = 30)]
        public ActionResult Img(string id, int? width, int? height)
        {
            try
            {
                if (string.IsNullOrEmpty(id))
                {
                    return Content("");
                }

                string imgName = id;
                if (null != width && null != height)
                {
                    imgName += "_" + width + "_" + height;
                }

                #region ETag缓存处理

                //var requestedETag = Request.Headers["If-None-Match"];
                //var responseETag = imgName; // lookup or generate etag however you want
                //if (requestedETag == responseETag)
                //{
                //    return new HttpStatusCodeResult(HttpStatusCode.NotModified);
                //}

                #endregion

                //选择合适的图片路径
                string saveFilePath = ImageService.ChoosePath(id, imgName);

                //不存在该图片
                if (!System.IO.File.Exists(saveFilePath))
                {
                    //判断源文件是否存在
                    string sourceSaveFilePath = ImageService.ChoosePath(id, id);

                    if (string.IsNullOrEmpty(sourceSaveFilePath) || !System.IO.File.Exists(sourceSaveFilePath))
                    {
                        return Content(GetIpAddress() + ",文件不存在");
                    }
                    //生成缩略图
                    ImageUtil.GetPicThumbnail(sourceSaveFilePath, saveFilePath, height.Value, width.Value);
                }

                using (var writer = new StreamWriter(HttpContext.Response.Body))
                {
                    Response.Clear();
                    //Response.Cache.SetAllowResponseInBrowserHistory(true);
                    //Response.Cache.SetExpires(DateTime.Now.AddYears(1));
                    //Response.Cache.SetOmitVaryStar(true);
                    Response.ContentType = Config.MIME;
                    using (FileStream stream = new FileStream(saveFilePath, FileMode.Open, FileAccess.Read))
                    {
                        int len = (int)stream.Length;
                        byte[] buffer = new byte[len];
                        stream.Read(buffer, 0, len);
                        writer.BaseStream.BeginWrite(buffer, 0, len,null,null);
                    };
                    writer.Flush();
                }

                return new EmptyResult();
            }
            catch (Exception ex)
            {
                return Content(GetIpAddress() + "," + ex.Message);
            }
        }

        private string GetIpAddress()
        {
            //string hostName = Dns.GetHostName();   //获取本机名
            //IPHostEntry localhost = Dns.GetHostByName(hostName);    //方法已过期，可以获取IPv4的地址
            //IPAddress localaddr = localhost.AddressList[0];

            var httpcontext = new IPHelper(_httpContextAccessor);

            return httpcontext.GetIP();
        }
    }

    public class ResultStruct
    {
        public string code;

        public string msg;

        public object obj;
    }
}
